package br.usjt.component.login.dao;

import static br.usjt.component.login.util.MessageUtil.MESSAGE_SEM_RESULTADO;

import java.util.Collections;
import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import br.com.usjt.component.commons.login.exceptions.NotResultException;
import br.usjt.component.login.facade.dao.LoginDao;
import br.usjt.component.login.model.Login;

public class LoginDaoImp extends GenericDaoImp<Login> implements LoginDao {

    private static final long serialVersionUID = 5861700563411251942L;

    public LoginDaoImp() {
        super(Login.class);
    }

    @Override
    public Login efetuarLogin(final String login, final String senha) {

        String jpql = "Select l from Login l where login = :login and senha = :senha and status is true";

        Query query = getEM().createQuery(jpql);
        query.setParameter("login", login);
        query.setParameter("senha", senha);

        try {
            return (Login) query.getSingleResult();
        } catch (NoResultException e) {
            throw new NotResultException(MESSAGE_SEM_RESULTADO, e);
        }

    }

    @Override
    public List<Login> findByAllActives() {

        String jpql = "Select l from Login l where status is true";

        Query query = getEM().createQuery(jpql);

        @SuppressWarnings("unchecked")
        List<Login> resultList = query.getResultList();

        if (resultList.isEmpty()) {
            return Collections.emptyList();
        }

        return resultList;
    }

    @Override
    public List<Login> findByAllInactives() {
        String jpql = "Select l from Login l where status is false";

        Query query = getEM().createQuery(jpql);

        @SuppressWarnings("unchecked")
        List<Login> resultList = query.getResultList();

        if (resultList.isEmpty()) {
            return Collections.emptyList();
        }

        return resultList;
    }

}
